from django.http import HttpResponse
from rest_framework import viewsets

from library_app.models import Category, Author, Book
from library_app.serializers import CategorySerializer, AuthorSerializer, BookReadSerializer, BookWriteSerializer
import json
from collections import Counter


def books_num(request):
    #书本总数
    json_str={
        "count":Book.objects.all().count()
    }
    return HttpResponse(json.dumps(json_str))

def books_cost(request):
    #书本总价
    total_list=[ i["price"] for i in list(Book.objects.all().values('price'))]
    json_str={
        "total_books_cost":sum(total_list)
    }
    return HttpResponse(json.dumps(json_str))

def mostAuthor(request):
    #最多的作者
    total_list=[ i["author"] for i in list(Book.objects.all().values('author'))]
    count = Counter(total_list)
    max_prices = max(zip(count.values(), count.keys()))
    most_num=Author.objects.all()[max_prices[1]-1]
    print(most_num)
    json_str={
        "total_books_cost":str(most_num)
    }
    return HttpResponse(json.dumps(json_str))

def mostCategory(request):
    #最多的分类
    total_list=[ i["category"] for i in list(Book.objects.all().values('category'))]
    count = Counter(total_list)
    max_prices = max(zip(count.values(), count.keys()))
    most_num=Category.objects.all()[max_prices[1]-1]
    print(most_num)
    json_str={
        "total_books_cost":str(most_num)
    }
    return HttpResponse(json.dumps(json_str))



class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    def get_serializer_class(self):
        if self.request.method in ['GET', 'HEAD']:
            return BookReadSerializer
        else:
            return BookWriteSerializer

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    

class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer
